<template>

  <div class="app-container">
    <a-card style="margin-bottom: 16px">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="单位" prop="schoolId">
          <el-select @change="onchangeSchool" clearable v-model="queryParams.schoolId" placeholder="请选择">
            <el-option
                v-for="item in schoolList"
                :key="item.id"
                :label="item.unitName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组别" prop="schoolId">
          <el-select @change="onchangeSchool" clearable v-model="queryParams.groupId" placeholder="请选择">
            <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.gropuName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item style="flex: 1">
          <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>

        <el-form-item style="flex: 1">
          <el-button type="primary" icon="Present" @click="piliangLottery">批量抽签</el-button>


        </el-form-item>
      </el-form>
    </a-card>

    <el-row :gutter="20">
      <!--部门数据-->
      <el-col style="height: 100%" :span="6" :xs="24">
        <a-card title="项目选择">
          <div style="height: 100%;display: flex;flex-direction: column;flex: 1">
            <div class="head-container">
              <el-input
                  v-model="subName"
                  placeholder="请输入项目名称"
                  clearable
                  prefix-icon="Search"
                  style="margin-bottom: 20px"
              />
            </div>
            <div class="head-container">
              <el-tree
                  style="height: 480px;overflow-y: scroll"
                  :data="subjectOptions"
                  :props="{ label: 'label', children: 'children' }"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="deptTreeRef"
                  node-key="id"
                  highlight-current
                  default-expand-all
                  @node-click="handleNodeClick"
              />
            </div>
          </div>
        </a-card>
      </el-col>
      <!--用户数据-->
      <el-col style="height: 100%" :span="18" :xs="24">

        <a-card title="赛中编号抽签" v-if="selectSubject.type!=null || selectSubject.lottery!=0">
          <template #extra>
            <el-button type="primary" icon="Present" @click="outputLotteryWord">导出抽签登记表</el-button>
            <el-button type="primary" icon="Present" @click="outputJianlu">导出检录表</el-button>
            <el-button type="primary" icon="Present" @click="outputExcel">导出抽签汇总表</el-button>
          </template>
          <el-table v-loading="tableLoading" style="height: 480px;" :data="orchestrateList">
            <el-table-column label="名称" align="center" prop="name"/>
            <el-table-column v-if="selectSubject.type==1 || selectSubject.lottery==1" label="性别" align="center"
                             prop="sex">
              <template #default="scope">
                <dict-tag :options="teacher_sex_type" :value="scope.row.sex"/>
              </template>
            </el-table-column>

            <el-table-column v-if="selectSubject.lottery!=1" label="赛中编号" align="center" prop="no"/>
            <el-table-column label="组别" align="center" prop="groupName"/>
            <el-table-column v-if="selectSubject.code=='lsmp' || selectSubject.code=='pdjx'" label="序号" align="center"
                             prop="xh"/>

            <el-table-column v-if="selectSubject.lottery==1" label="项目" align="center" prop="subName"/>

            <el-table-column width="160" label="单位" align="center" prop="unitName">
              <template #default="scope">
                <span v-if="selectSubject.type == 1">
                  {{ scope.row.unitName }}
                </span>
                <span v-if="selectSubject.type == 2">
                  {{ scope.row.name }}
                </span>
              </template>
            </el-table-column>

            <el-table-column fixed="right" width="200" label="操作" align="center"
                             class-name="small-padding fixed-width">

              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                           v-hasPermi="['business:student:edit']">修改
                </el-button>
                <el-button link type="primary" icon="DeploymentUnitOutlined" @click="lottery(scope.row)"
                           v-hasPermi="['business:student:edit']">抽签
                </el-button>

              </template>
            </el-table-column>
          </el-table>
          <pagination
              v-show="total>0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
          />
        </a-card>
        <a-card v-else>
          <a-empty>
            <template #description>
              <span>
                无需操作
              </span>
            </template>
          </a-empty>
        </a-card>

      </el-col>
    </el-row>

    <a-modal centered v-model:open="editShow" title="编辑">
      <el-form :model="updateItem" :rules="rules" label-width="80px">
        <el-form-item label="赛中编号" prop="no">
          <el-input v-model="updateItem.no" placeholder="请输入赛中编号"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmUpdate">确 定</el-button>
          <el-button @click="editShow=false">取 消</el-button>
        </div>
      </template>
    </a-modal>

    <a-modal centered v-model:open="schoolStuShow" title="批量抽签">
      <el-table height="420" :data="piliangOrchestrateList">
        <el-table-column label="名称" align="center" prop="name"/>
        <el-table-column v-if="selectSubject.type==1 || selectSubject.lottery==1" label="性别" align="center"
                         prop="sex">
          <template #default="scope">
            <dict-tag :options="teacher_sex_type" :value="scope.row.sex"/>
          </template>
        </el-table-column>

        <el-table-column  label="赛中编号" align="center" prop="no"/>

        <el-table-column width="160" label="单位" align="center" prop="unitName">
          <template #default="scope">
                <span v-if="selectSubject.type == 1">
                  {{ scope.row.unitName }}
                </span>
            <span v-if="selectSubject.type == 2">
                  {{ scope.row.name }}
                </span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="lotteryList">抽 签</el-button>

          <el-button @click="schoolStuShow=false">取 消</el-button>
        </div>
      </template>
    </a-modal>
  </div>


</template>

<script>
import {deptTreeSelect} from "@/api/business/subject";
import {list, update, lottery, outputExcel} from "@/api/business/orchestrate";
import {ref, watch} from 'vue';
import {listSchool} from "@/api/business/school.js";
import { listGroup, getGroup, delGroup, addGroup, updateGroup } from "@/api/business/group";
import { listUnit} from "@/api/business/unit";
import {message} from "ant-design-vue";

export default {
  name: "LotteryPage",
  data() {
    const {proxy} = getCurrentInstance();
    const subName = ref("");
    const {base_confirm_status, teacher_sex_type} = proxy.useDict('base_confirm_status', 'teacher_sex_type');
    watch(subName, (newVal, oldVal) => {
      this.$refs["deptTreeRef"].filter(newVal);
    });
    const channel = new BroadcastChannel('enterScore');
    let queryParams = {
      subId: null,
      pageNum: 1,
      pageSize: 10,
      schoolId: null,
      no: null,
      avatarSrc: null,
      name: null,
      stuNo: null,
      className: null,
      nation: null,
      sex: null,
      birth: null,
      birthPlace: null,
      cardId: null,
      mailAddress: null,
      mobile: null,
      oneConfirm: null,
      oneConfirmTime: null,
      twoConfirm: null,
      twoConfirmTime: null,
      editShow: true,
      schoolList: [],
      tableLoading: true,
      groupList:[],
    };
    return {
      teacher_sex_type,
      showSearch: true,
      subjectOptions: [],
      subName,
      selectSubject: {},
      orchestrateList: [],
      queryParams,
      total: 0,
      form: {},
      editShow: false,
      updateItem: {},
      proxy,
      schoolStuShow: false,
      piliangOrchestrateList: [],
      channel,
    }

  },
  mounted() {
    this.getSchoolList();
    this.getGroupList();
    this.getDeptTree();
    /** 根据名称筛选部门树 */

  },
  // watch(){
  //
  // },
  beforeUnmount() {

  },

  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      let that = this;
      deptTreeSelect().then(response => {
        console.log(response)
        that.subjectOptions = response.data;
      });
    },
    outputExcel() {
      let that = this;
      this.proxy.download('business/orchestrate/outputExcel', {}, `抽签表-${new Date().getTime()}.xlsx`)
    },
    outputJianlu() {
      let that = this;
      this.proxy.download('business/orchestrate/outputJianlu', {
        subId: this.queryParams.subId,
        groupId: this.queryParams.groupId
      }, `检录表-${new Date().getTime()}.docx`)
    },
    outputLotteryWord() {
      let that = this;
      this.proxy.download('business/orchestrate/outputLotteryWord', {
        subId: this.queryParams.subId,
        groupId: this.queryParams.groupId
      }, `抽签结果表-${new Date().getTime()}.docx`)
    },
    /** 通过条件过滤节点  */
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 节点单击事件 */
    handleNodeClick(data) {
      let that = this;
      this.selectSubject = data.baseSubject;
      this.queryParams.subId = data.baseSubject.id;
      this.queryParams.type = data.baseSubject.type;
      this.getList();
    },
    getList() {
      let that = this;
      if (this.queryParams.subId == null) {
        return;
      }
      that.orchestrateList = [];
      that.tableLoading = true;
      list(this.queryParams).then(response => {
        console.log(response)
        that.orchestrateList = response.rows;
        that.total = response.total;
        that.tableLoading = false;
      }).catch(err => {
        that.orchestrateList = [];
        that.total = 0;
        that.tableLoading = false;
      });
    },
    async lotteryList() {
      const key = 'updatable';
      message.loading('抽签中', key, 0);
      let that = this;
      for (let i = 0; i < this.piliangOrchestrateList.length; i++) {
        console.log(this.piliangOrchestrateList[i]);
        console.log("start");
        this.piliangOrchestrateList[i].groupId = this.queryParams.groupId;
        await lottery(this.piliangOrchestrateList[i]).then(response => {
          console.log(response.data);
          that.piliangOrchestrateList[i] = response.data;
        })
      }
      message.success({content: '抽签完成!', key, duration: 2});
      this.getList();
    },
    lottery(item) {
      let that = this;
      console.log(item);
      this.updateItem = item;
      this.updateItem.groupId = this.queryParams.groupId;
      const key = 'updatable';
      message.loading('抽签中', key, 0);
      lottery(this.updateItem).then(response => {
        that.getList();
        message.success({content: '抽签完成!', key, duration: 2});
      })
    },
    handleUpdate(item) {
      console.log(item);
      this.updateItem = item;
      this.editShow = true;

    },
    confirmUpdate() {
      let that = this;
      update(this.updateItem).then(response => {
        that.editShow = false;
        that.getList();
        console.log(response)
      })
    },
    /** 查询学校列表 */
    getSchoolList() {
      let that = this;
      listUnit(
          {pageSize: 0}
      ).then(response => {
        that.schoolList = response.rows;
      });
    },
    getGroupList(){
      let that = this;
      listGroup(
          {pageSize: 0}
      ).then(response => {
        that.groupList = response.rows;
        that.groupList.push({
          gropuName:'全部组别',
          id:-1,
        })
      });
    },
    piliangLottery() {
      this.schoolStuShow = true
      let that = this;
      if (this.queryParams.subId == null) {
        return;
      }
      let params = {};
      params.pageSize = 1000;
      params.subId = this.queryParams.subId;
      params.pageNum = 1;
      params.unitId = this.queryParams.schoolId;
      params.type = this.queryParams.type;
      params.groupId = this.queryParams.groupId;
      list(params).then(response => {
        console.log(response)
        that.piliangOrchestrateList = response.rows;
      }).catch(err => {
        that.piliangOrchestrateList = [];
      });

      let sendInfo = {
        params,
        type: 'lottery',
      }
      console.log(this.channel)
      this.channel.postMessage(sendInfo);
    },
    onchangeSchool(e) {
      this.getList();
    }
  }
}
</script>

<style>
</style>
